// 完整的登录功能测试 - 检查前后端集成
console.log('===============================');
console.log('  空气质量监控系统 - 登录测试  ');
console.log('===============================');

// 模拟环境
const localStorage = global.localStorage || {
  _data: {},
  getItem(key) {
    return this._data[key];
  },
  setItem(key, value) {
    this._data[key] = value;
    console.log(`[LocalStorage] 设置 ${key}: ${value.substring(0, 20)}${value.length > 20 ? '...' : ''}`);
  },
  removeItem(key) {
    delete this._data[key];
    console.log(`[LocalStorage] 删除 ${key}`);
  },
  clear() {
    this._data = {};
    console.log(`[LocalStorage] 清空所有数据`);
  }
};

// 配置
const config = {
  apiUrl: 'https://zmyzmy.xin/api',
  username: 'admin',
  password: '123456',
  debugMode: true
};

// 日志函数
const logger = {
  info: (msg, data) => {
    console.log(`[信息] ${msg}`);
    if (data && config.debugMode) console.log(data);
  },
  error: (msg, error) => {
    console.log(`[错误] ${msg}`);
    if (error && config.debugMode) console.log(error);
  },
  success: (msg, data) => {
    console.log(`[成功] ${msg}`);
    if (data && config.debugMode) console.log(data);
  },
  warn: (msg, data) => {
    console.log(`[警告] ${msg}`);
    if (data && config.debugMode) console.log(data);
  }
};

// 登录测试
async function testLogin() {
  logger.info(`尝试登录 - 用户名: ${config.username}, 密码: ${'*'.repeat(config.password.length)}`);
  
  try {
    // 执行登录请求
    const response = await fetch(`${config.apiUrl}/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        username: config.username,
        password: config.password
      })
    });
    
    const data = await response.json();
    
    logger.info(`登录响应状态码: ${response.status}`);
    
    if (response.ok && data.code === 200 && data.data?.token) {
      // 保存token和用户信息
      const token = data.data.token;
      localStorage.setItem('token', `Bearer ${token}`);
      
      if (data.data.userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(data.data.userInfo));
      }
      
      // 解析token
      try {
        const tokenParts = token.split('.');
        if (tokenParts.length === 3) {
          const payload = JSON.parse(atob(tokenParts[1]));
          logger.info('Token解析成功', payload);
          
          // 保存token过期时间
          const expiresAt = payload.exp * 1000;
          localStorage.setItem('tokenExpires', expiresAt.toString());
          
          const now = Date.now();
          const expiresIn = Math.floor((expiresAt - now) / (1000 * 60 * 60));
          logger.info(`Token有效期还剩约 ${expiresIn} 小时`);
        }
      } catch (e) {
        logger.warn('解析Token时出错', e);
      }
      
      logger.success('登录成功！');
      return true;
    } else {
      logger.error('登录失败', data);
      return false;
    }
  } catch (error) {
    logger.error('请求异常', error);
    return false;
  }
}

// 测试API状态
async function testApiStatus() {
  logger.info('检查API状态...');
  
  try {
    const token = localStorage.getItem('token');
    
    const response = await fetch(`${config.apiUrl}/auth/test`, {
      headers: {
        'Accept': 'application/json',
        'Authorization': token
      }
    });
    
    const data = await response.json();
    
    if (response.ok) {
      logger.success('API状态检查成功', data);
      return true;
    } else {
      logger.error('API状态检查失败', data);
      return false;
    }
  } catch (error) {
    logger.error('API状态检查异常', error);
    return false;
  }
}

// 运行测试
(async () => {
  logger.info('开始登录测试流程');
  
  // 清除之前的登录状态
  localStorage.clear();
  
  // 测试登录
  const loginSuccess = await testLogin();
  
  if (loginSuccess) {
    // 测试API状态
    await testApiStatus();
  }
  
  logger.info('登录测试流程结束');
})();
